package com.anpy.common.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

//@Component
//@RestControllerAdvice(basePackages = "com.anpy")
@Slf4j
public class ValidationExceptionResovler extends AbstractHandlerExceptionResolver {
    public ValidationExceptionResovler() {
        // 设置order，在DefaultHandlerExceptionResolver之前执行
        this.setOrder(0);
    }


//    @ResponseBody
    protected ModelAndView handleMethodArgumentNotValidException(BindingResult bindingResult,
                                                                 HttpServletRequest request,
                                                                 HttpServletResponse response,
                                                                 Object handler)
            throws IOException {

        List<ObjectError> errors = bindingResult.getAllErrors();
        StringBuilder errmsgBF = new StringBuilder();
        for (ObjectError error : errors) {
            String massage = error.getDefaultMessage();
            if (errmsgBF.length() == 0) {
                errmsgBF.append(massage);
            }

//            errmsgBF.append("||");
        }
        String errmsgString = errmsgBF.toString();
//        errmsgString = errmsgString.length() > 2 ? errmsgString.substring(0, errmsgString.length() - 2) : errmsgString;
        log.error("Validation failed! {} ", errmsgString);

        Map<String, Object> map = new TreeMap<>();
        map.put("result", "300");
        map.put("message", errmsgString);

        ModelAndView mav = new ModelAndView();
        MappingJackson2JsonView view = new MappingJackson2JsonView();
        view.setAttributesMap(map);
        mav.setView(view);

        return mav;
    }

//    @Override
    protected ModelAndView doResolveException(HttpServletRequest request,
                                              HttpServletResponse response, Object handler,
                                              Exception ex) {
         BindingResult bindingResult = null;
        if (ex instanceof MethodArgumentNotValidException) {
            bindingResult = ((MethodArgumentNotValidException) ex).getBindingResult();
        } else if (ex instanceof BindException) {
            bindingResult = ((BindException) ex).getBindingResult();
        }

        if (bindingResult != null) {
            try {
                return handleMethodArgumentNotValidException(bindingResult, request, response, handler);
            } catch (IOException e) {
                log.error("doResolveException: ", e);
            }
        }

        Map<String, Object> map = new TreeMap<>();
        map.put("result", "500");
        map.put("message", "服务器异常");
        ModelAndView mav = new ModelAndView();
        MappingJackson2JsonView view = new MappingJackson2JsonView();
        view.setAttributesMap(map);
        mav.setView(view);

        return mav;
    }
}